{% extends "base.html" %}

{% block content %}
<div class="max-w-7xl mx-auto">
    <div class="flex items-center justify-between mb-6">
        <div>
            <h1 class="text-2xl font-bold text-gray-900">Documents</h1>
            <p class="text-gray-600">Browse and manage your regulatory documents</p>
        </div>
        <button 
            onclick="location.href='/upload'"
            class="bg-indigo-600 text-white px-4 py-2 rounded-lg hover:bg-indigo-700 flex items-center space-x-2"
        >
            <i class="fas fa-plus"></i>
            <span>Upload Document</span>
        </button>
    </div>

    <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-4 mb-6">
        <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">Search by File Name</label>
                <input 
                    type="text" 
                    placeholder="Search documents..."
                    class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500"
                    id="documentSearch"
                >
            </div>
            
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">Collection</label>
                <select id="collectionFilter" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500">
                    <option value="">All Collections</option>
                </select>
            </div>
            
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">Status</label>
                <select id="statusFilter" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500">
                    <option value="">All Status</option>
                    <option value="Draft">Draft</option>
                    <option value="Effective">Effective</option>
                    <option value="Expired">Expired</option>
                </select>
            </div>
        </div>
    </div>

    <div class="flex items-center justify-between mb-4">
        <div class="text-sm text-gray-500" id="documentCount">
            Showing <span class="font-medium">0</span> documents
        </div>
    </div>

    <div class="bg-white rounded-xl shadow-sm border border-gray-200">
        <div class="grid grid-cols-12 gap-4 px-6 py-3 bg-gray-50 border-b border-gray-200 text-sm font-medium text-gray-700">
            <div class="col-span-3">File Name</div>
            <div class="col-span-2">Country/Region</div>
            <div class="col-span-2">Regulation ID</div>
            <div class="col-span-2">Issuing Authority</div>
            <div class="col-span-1">Status</div>
            <div class="col-span-2 text-right">Actions</div>
        </div>
        
        <div id="documentsList"></div>
        
        <div id="loadingState" class="p-8 text-center">
            <div class="animate-spin rounded-full h-8 w-8 border-b-2 border-indigo-600 mx-auto"></div>
            <p class="mt-2 text-gray-500">Loading documents...</p>
        </div>
        
        <div id="emptyState" class="hidden p-8 text-center">
            <i class="fas fa-folder-open text-gray-300 text-4xl mb-3"></i>
            <p class="text-gray-500">No documents found</p>
        </div>
    </div>

    <div class="flex items-center justify-between mt-6">
        <div class="text-sm text-gray-500" id="paginationInfo">
            Showing <span id="startCount">0</span> to <span id="endCount">0</span> of <span id="totalCount">0</span> documents
        </div>
        <div class="flex space-x-2" id="paginationControls"></div>
    </div>
</div>

<div id="deleteModal" class="hidden fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
    <div class="bg-white rounded-xl max-w-md w-full mx-4 p-6">
        <div class="flex items-center space-x-3 mb-4">
            <div class="w-10 h-10 bg-red-100 rounded-full flex items-center justify-center">
                <i class="fas fa-exclamation-triangle text-red-600"></i>
            </div>
            <h3 class="text-lg font-semibold text-gray-900">Delete Document</h3>
        </div>
        <p class="text-gray-600 mb-6">Are you sure you want to delete this document? This action cannot be undone.</p>
        <div class="flex justify-end space-x-3">
            <button onclick="closeDeleteModal()" class="px-4 py-2 border border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50">
                Cancel
            </button>
            <button onclick="confirmDelete()" class="px-4 py-2 bg-red-600 text-white rounded-lg hover:bg-red-700">
                Delete
            </button>
        </div>
    </div>
</div>
{% endblock %}

{% block scripts %}
<script>
let currentPage = 1;
const pageSize = 20;
let totalDocuments = 0;
let currentDocuments = [];
let documentToDelete = null;

document.addEventListener('DOMContentLoaded', async () => {
    await loadCollectionsForFilter();
    
    // Check URL parameters
    const urlParams = new URLSearchParams(window.location.search);
    const collectionParam = urlParams.get('collection');
    if (collectionParam) {
        document.getElementById('collectionFilter').value = collectionParam;
    }
    
    await loadDocuments();
    setupEventListeners();
});

async function loadCollectionsForFilter() {
    try {
        const response = await fetch('/api/collections/list');
        const data = await response.json();
        if (data.status === 'success') {
            const select = document.getElementById('collectionFilter');
            data.collections.forEach(collection => {
                const option = document.createElement('option');
                option.value = collection.name;
                option.textContent = collection.display_name || collection.name;
                select.appendChild(option);
            });
        }
    } catch (error) {
        console.error('Error loading collections:', error);
    }
}

async function loadDocuments() {
    try {
        showLoadingState();
        
        const searchQuery = document.getElementById('documentSearch').value;
        const collection = document.getElementById('collectionFilter').value;
        const status = document.getElementById('statusFilter').value;
        
        const params = new URLSearchParams({
            page: currentPage,
            limit: pageSize
        });
        
        if (searchQuery) params.append('search', searchQuery);
        if (collection) params.append('collection', collection);
        if (status) params.append('status', status);
        
        const response = await fetch(`/api/documents?${params}`);
        const data = await response.json();
        
        if (data.status === 'success') {
            currentDocuments = data.documents;
            totalDocuments = data.total || data.documents.length;
            renderDocuments();
            updatePagination();
            updateDocumentCount();
        } else {
            throw new Error(data.message);
        }
    } catch (error) {
        console.error('Error loading documents:', error);
        showEmptyState('Error loading documents');
    }
}

function renderDocuments() {
    const container = document.getElementById('documentsList');
    
    if (currentDocuments.length === 0) {
        showEmptyState();
        return;
    }
    
    hideEmptyState();
    hideLoadingState();
    
    container.innerHTML = '';
    
    const statusColors = {
        'Draft': 'bg-yellow-100 text-yellow-800',
        'Effective': 'bg-green-100 text-green-800',
        'Expired': 'bg-red-100 text-red-800'
    };
    
    currentDocuments.forEach(doc => {
        const row = document.createElement('div');
        row.className = 'grid grid-cols-12 gap-4 px-6 py-4 border-b border-gray-100 hover:bg-gray-50';
        
        const status = doc.status || 'Unknown';
        const statusColor = statusColors[status] || 'bg-gray-100 text-gray-800';
        const displayFileName = doc.file_name || doc.display_name || doc.filename || 'Unknown';
        
        row.innerHTML = `
            <div class="col-span-3">
                <button onclick="viewDocument('${doc._id}')" class="text-indigo-600 hover:text-indigo-800 font-medium text-left">
                    <i class="fas fa-file-alt mr-2"></i>${displayFileName}
                </button>
            </div>
            <div class="col-span-2 text-gray-600">${doc.country || ''}</div>
            <div class="col-span-2 text-gray-600">${doc.regulation_id || '-'}</div>
            <div class="col-span-2 text-gray-600">${doc.issuing_authority || ''}</div>
            <div class="col-span-1">
                <span class="px-2 py-1 text-xs font-medium rounded-full ${statusColor}">
                    ${status}
                </span>
            </div>
            <div class="col-span-2 text-right">
                <div class="flex items-center justify-end space-x-2">
                    <button onclick="viewDocument('${doc._id}')" class="text-blue-600 hover:text-blue-800" title="View">
                        <i class="fas fa-eye"></i>
                    </button>
                    <button onclick="editDocument('${doc._id}')" class="text-green-600 hover:text-green-800" title="Edit">
                        <i class="fas fa-edit"></i>
                    </button>
                    <button onclick="openDeleteModal('${doc._id}')" class="text-red-600 hover:text-red-800" title="Delete">
                        <i class="fas fa-trash"></i>
                    </button>
                </div>
            </div>
        `;
        
        container.appendChild(row);
    });
}

function setupEventListeners() {
    let searchTimeout;
    document.getElementById('documentSearch').addEventListener('input', (e) => {
        clearTimeout(searchTimeout);
        searchTimeout = setTimeout(() => {
            currentPage = 1;
            loadDocuments();
        }, 300);
    });
    
    document.getElementById('collectionFilter').addEventListener('change', () => {
        currentPage = 1;
        loadDocuments();
    });
    
    document.getElementById('statusFilter').addEventListener('change', () => {
        currentPage = 1;
        loadDocuments();
    });
}

function updatePagination() {
    const start = (currentPage - 1) * pageSize + 1;
    const end = Math.min(currentPage * pageSize, totalDocuments);
    
    document.getElementById('startCount').textContent = totalDocuments > 0 ? start : 0;
    document.getElementById('endCount').textContent = end;
    document.getElementById('totalCount').textContent = totalDocuments;
    
    const controls = document.getElementById('paginationControls');
    const totalPages = Math.ceil(totalDocuments / pageSize);
    
    controls.innerHTML = '';
    
    if (totalPages <= 1) return;
    
    const prevButton = document.createElement('button');
    prevButton.className = `px-3 py-1 border border-gray-300 rounded ${currentPage === 1 ? 'bg-gray-100 text-gray-400 cursor-not-allowed' : 'text-gray-700 hover:bg-gray-50'}`;
    prevButton.innerHTML = '<i class="fas fa-chevron-left"></i>';
    prevButton.disabled = currentPage === 1;
    prevButton.onclick = () => {
        if (currentPage > 1) {
            currentPage--;
            loadDocuments();
        }
    };
    controls.appendChild(prevButton);
    
    for (let i = 1; i <= totalPages; i++) {
        if (totalPages <= 7 || i === 1 || i === totalPages || (i >= currentPage - 1 && i <= currentPage + 1)) {
            const pageButton = document.createElement('button');
            pageButton.className = `px-3 py-1 border border-gray-300 ${currentPage === i ? 'bg-indigo-600 text-white' : 'text-gray-700 hover:bg-gray-50'}`;
            pageButton.textContent = i;
            pageButton.onclick = () => {
                currentPage = i;
                loadDocuments();
            };
            controls.appendChild(pageButton);
        } else if (i === currentPage - 2 || i === currentPage + 2) {
            const ellipsis = document.createElement('span');
            ellipsis.className = 'px-2 text-gray-400';
            ellipsis.textContent = '...';
            controls.appendChild(ellipsis);
        }
    }
    
    const nextButton = document.createElement('button');
    nextButton.className = `px-3 py-1 border border-gray-300 rounded ${currentPage === totalPages ? 'bg-gray-100 text-gray-400 cursor-not-allowed' : 'text-gray-700 hover:bg-gray-50'}`;
    nextButton.innerHTML = '<i class="fas fa-chevron-right"></i>';
    nextButton.disabled = currentPage === totalPages;
    nextButton.onclick = () => {
        if (currentPage < totalPages) {
            currentPage++;
            loadDocuments();
        }
    };
    controls.appendChild(nextButton);
}

function updateDocumentCount() {
    const countElement = document.getElementById('documentCount');
    countElement.innerHTML = `Showing <span class="font-medium">${currentDocuments.length}</span> documents`;
}

function showLoadingState() {
    document.getElementById('loadingState').classList.remove('hidden');
    document.getElementById('emptyState').classList.add('hidden');
    document.getElementById('documentsList').innerHTML = '';
}

function hideLoadingState() {
    document.getElementById('loadingState').classList.add('hidden');
}

function showEmptyState(message = 'No documents found') {
    document.getElementById('loadingState').classList.add('hidden');
    document.getElementById('documentsList').innerHTML = '';
    
    const emptyState = document.getElementById('emptyState');
    emptyState.querySelector('p').textContent = message;
    emptyState.classList.remove('hidden');
}

function hideEmptyState() {
    document.getElementById('emptyState').classList.add('hidden');
}

function viewDocument(docId) {
    window.location.href = `/view/${docId}`;
}

function editDocument(docId) {
    window.location.href = `/edit/${docId}`;
}

function openDeleteModal(docId) {
    documentToDelete = docId;
    document.getElementById('deleteModal').classList.remove('hidden');
}

function closeDeleteModal() {
    documentToDelete = null;
    document.getElementById('deleteModal').classList.add('hidden');
}

async function confirmDelete() {
    if (!documentToDelete) return;
    
    try {
        const response = await fetch(`/api/documents/${documentToDelete}`, {
            method: 'DELETE'
        });
        
        const data = await response.json();
        
        if (data.status === 'success') {
            closeDeleteModal();
            await loadDocuments();
        } else {
            alert('Error deleting document: ' + data.message);
        }
    } catch (error) {
        console.error('Error deleting document:', error);
        alert('Error deleting document');
    }
}

document.getElementById('deleteModal').addEventListener('click', (e) => {
    if (e.target.id === 'deleteModal') {
        closeDeleteModal();
    }
});
</script>
{% endblock %}